/*
 *===========================================================================
 *
 *          Name: jksocket.c
 *        Create: 2013年08月24日 星期六 13时22分21秒
 *
 *   Discription: some socket func
 *
 *         Email: jmdkina@gmail.com
 *
 *===========================================================================
 */

#include <stdio.h>
#include <strings.h>

#include <sys/types.h>
#include <sys/socket.h>

#include "jksocket.h"

/**
 * return -1: socket error
 *        -2: gethostbyname error
 *        -3: connect error
 */
int jk_open_clientfd(char *hostname, int port)
{
    int clientfd;
    struct hostent *hp;    // will use it if need dns info
    struct sockaddr_in serveraddr;

    if ((clientfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
        return -1;

    /* if you need dns info */
    if ((hp = gethostbyname(hostname)) == NULL) {
        return -2;
    }

    bzero((char*)&serveraddr, sizeof(serveraddr));
    serveraddr.sin_family = AF_INET;
    bcopy((char*)hp->h_addr_list[0], (char*)&serveraddr.sin_addr.s_addr, hp->h_length);
    serveraddr.sin_port = htons(port);

    if (connect(clientfd, (SA*)&serveraddr, sizeof(serveraddr)) < 0)
        return -3;

    return 0;
}

/**
 * return -1: socket error
 *        -2: setsockopt error
 *        -3: bind error
 *        -4: listen error
 */
int jk_open_listenfd(int port)
{
    int listenfd, optval = 1;
    struct sockaddr_in serveraddr;

    if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
        return -1;

    if (setsocketopt(listenfd, SOL_SOCKET, SO_REUSEADDR, 
               (const void*)&optval, sizeof(int)) < 0)
        return -2;

    bzero((char*)&serveraddr, sizeof(serveraddr));
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
    serveraddr.sin_port = htons((unsigned short)port);

    if (bind(listenfd, (SA*)&serveraddr, sizeof(serveraddr)) < 0)
        return -3;

    if (listen(listenfd, LISTENQ) < 0)
        return -4;

    return listenfd;
}

/*=============== End of file: jksocket.c ==========================*/
